package com.tudouji.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.sword.lang.HttpUtils;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 通过经度纬度计算位置距离 KM
 *
 * @author xxl
 *
 */
public class LocationCount {
	private static double EARTH_RADIUS = 6378.137;

	/**
	 * 根据两个位置的经纬度，来计算两地的距离（单位为KM） 参数为String类型
	 *
	 * @param lat1
	 *            用户经度
	 * @param lng1
	 *            用户纬度
	 * @param lat2
	 *            商家经度
	 * @param lng2
	 *            商家纬度
	 * @return
	 */
	public static String countDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
		Double lat1 = Double.parseDouble(lat1Str);
		Double lng1 = Double.parseDouble(lng1Str);
		Double lat2 = Double.parseDouble(lat2Str);
		Double lng2 = Double.parseDouble(lng2Str);
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double difference = radLat1 - radLat2;
		double mdifference = rad(lng1) - rad(lng2);
		double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
		distance = distance * EARTH_RADIUS;
		distance = Math.round(distance * 10000) / 10000;
		String distanceStr = distance + "";
		distanceStr = distanceStr.substring(0, distanceStr.indexOf("."));
		return distanceStr;
	}

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
		StringBuffer url = new StringBuffer();
		url.append("http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=");
		url.append(lat1Str + "," + lng1Str);
		url.append("&destinations=");
		url.append(lat2Str + "," + lng2Str);
		url.append("&ak=qDBibhYp1cKjd76cGGXGUzSPPI7ysoqx");
		String result = HttpUtils.get(url.toString());
		JSONObject jsonObject = JSONObject.parseObject(result);
		String str = jsonObject.getString("result");
		if (str == null) {
			return "0";
		}
		str = str.substring(1, str.length() - 1);
		JSONObject jsonObject1 = JSONObject.parseObject(str);
		JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.getString("distance"));
		return jsonObject2.getString("text");
	}

	public static String[] getAddressPoint(String address) {
		String[] point = new String[2];
		// http://api.map.baidu.com/geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
		// //GET请求
		StringBuffer url = new StringBuffer();
		url.append("http://api.map.baidu.com/geocoder/v2/?output=json");
		url.append("&address=");
		url.append(address);
		url.append("&ak=qDBibhYp1cKjd76cGGXGUzSPPI7ysoqx");
		String result = HttpUtils.get(url.toString());
		System.out.println(result);
		// {"status":0,"result":{"location":{"lng":111.75550856170946,"lat":40.84842299711348},"precise":0,"confidence":10,"comprehension":100,"level":"城市"}}
		JSONObject jsonObject = JSONObject.parseObject(result);
		String status = jsonObject.getString("status");
		if ("0".equalsIgnoreCase(status)){
            JSONObject res = jsonObject.getJSONObject("result");
            JSONObject location = res.getJSONObject("location");
            point[0] = location.getString("lat");
            point[1] = location.getString("lng");
        }
		return point;
	}

	/**
	 * 根据经纬度查询
	 * @param log
	 * @param lat
	 * @return
	 */
	public static String getAdd(String log, String lat ){
		//lat 小  log  大
		//参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
		String urlString = "http://api.map.baidu.com/geocoder/v2/?ak=qDBibhYp1cKjd76cGGXGUzSPPI7ysoqx&location="+ lat + "," + log + "&output=json";
		String res = "";
		try {
			URL url = new URL(urlString);
			java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				res += line+"\n";
			}
			in.close();
		} catch (Exception e) {
			System.out.println("error in wapaction,and e is " + e.getMessage());
		}
		return res;
	}
	/**
	 * 解析地址
	 * @return
	 */

	public static void main(String[] args){
//		String add = getAdd(111.735245+"",40.80594+"");
//		JSONObject obj = JSONObject.parseObject(add);
//		JSONObject resultObj = obj.getJSONObject("result");
//		String address = resultObj.getString("formatted_address");
//		System.out.println(address);

//		String[] pois = getAddressPoint("内蒙古乌兰察布市集宁区白海子镇泉脑村");
//		System.out.println(pois[0]);
//		System.out.println(pois[1]);
//		System.out.println(Date.parse("2023-08-24"));
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		System.out.println(DateUtils.getDate());
		try {
			System.out.println(sdf1.format(1692806400000L));
			System.out.println(sdf.parse(DateUtils.getDate()).getTime());
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

}
